import { ref, computed } from 'vue'
import { questionApi } from '@/api/question'
import { userApi } from '@/api/user'

export function useStats() {
  // 题目统计数据
  const questionStats = ref({
    total_questions: 0,
    difficulty_stats: {
      easy: 0,
      medium: 0,
      hard: 0
    },
    popular_questions: 0
  })
  
  // 用户统计数据
  const userStats = ref({
    solved_count: 0,
    total_submissions: 0,
    accepted_submissions: 0,
    acceptance_rate: 0,
    consecutive_days: 0,
    difficulty_stats: {
      easy_solved: 0,
      medium_solved: 0,
      hard_solved: 0
    }
  })
  
  // 计算属性
  const statsData = computed(() => ({
    total: questionStats.value.total_questions,
    solved: userStats.value?.solved_count || 0,
    rate: userStats.value?.acceptance_rate || 0,
    submissions: userStats.value?.total_submissions || 0
  }))
  
  // 方法
  const loadStats = async () => {
    try {
      // 加载题目统计
      const questionStatsResponse = await questionApi.getGlobalQuestionStats()
      if (questionStatsResponse.data) {
        questionStats.value = questionStatsResponse.data
      }
      
      // 加载用户统计（如果用户已登录）
      try {
        const userStatsResponse = await userApi.getCurrentUserStats()
        if (userStatsResponse.data) {
          userStats.value = userStatsResponse.data
        }
      } catch (error) {
        // 用户未登录，使用默认值
        console.log('用户未登录，使用默认统计数据')
      }
    } catch (error) {
      console.error('加载统计数据失败:', error)
    }
  }
  
  return {
    // 状态
    questionStats,
    userStats,
    
    // 计算属性
    statsData,
    
    // 方法
    loadStats
  }
}
